πŸ”‘ Java Keywords - Complete Interview Guide

Keywords Covered in This Guide

final static this super volatile transient synchronized instanceof

πŸ”Ή 1. final – Constant or Non-changeable

🧠 Meaning:

Used to prevent modification:

  • final variable β†’ value can't change
  • final method β†’ can't be overridden
  • final class β†’ can't be extended

πŸ”§ Syntax & Example:

final int x = 10;  // cannot change x again

final class Vehicle { }       // cannot be extended

class A {
    final void show() {
        System.out.println("Final method");
    }
}

🚫 Invalid:

x = 20; // ❌ Error: cannot assign a value to final variable

βœ… Use Cases:

  • Constants (final double PI = 3.14;)
  • Security (prevent overriding in sensitive classes)

πŸ”Ή 2. static – Belongs to Class, Not Object

🧠 Meaning:

  • Shared by all objects
  • Can be accessed without object creation
  • Used for memory efficiency and utility methods

πŸ”§ Syntax & Example:

class MyClass {
    static int count = 0; // shared across all objects

    static void display() {
        System.out.println("Static method");
    }
}

MyClass.display(); // No object needed

βœ… Use Cases:

  • Utility methods (Math.sqrt())
  • Shared counters
  • main() method is static so JVM can call it without object

πŸ”Ή 3. this – Refers to Current Object (Instance)

🧠 What is an Instance?

A class is like a blueprint, and an instance is a real object created from that class.
For example: Student s1 = new Student(); ← s1 is an instance of the Student class.

🧠 Meaning of this:

  • `this` refers to the current object (instance) inside a method or constructor.
  • Used when local variable names are the same as instance variables.
  • Also used to call another constructor or pass current object as argument.

πŸ”§ Example 1: Distinguishing Between Local and Instance Variables

class Student {
    int roll;  // instance variable

    Student(int roll) {
        this.roll = roll;  // this.roll = instance variable, roll = local variable
    }

    void show() {
        System.out.println("Roll number: " + this.roll);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student(101);
        s1.show();  // Output: Roll number: 101
    }
}

πŸ” Example 2: Constructor Chaining using this()

class Book {
    String title;
    int price;

    // No-argument constructor
    Book() {
        this("Java", 500);  // calls another constructor
    }

    Book(String title, int price) {
        this.title = title;
        this.price = price;
    }

    void show() {
        System.out.println(title + " - Rs." + price);
    }
}

πŸ“€ Example 3: Passing Current Object using this

class Person {
    void print(Person p) {
        System.out.println("This is: " + p);
    }

    void call() {
        print(this);  // passes current object to print()
    }
}

βœ… Use Cases of this:

  • To differentiate between local and instance variables.
  • To call one constructor from another using this().
  • To pass the current object as a parameter to a method.
  • To return the current object from a method (used in method chaining).

πŸ”Ή 4. super – Parent Class Reference

🧠 Meaning:

  • Used to refer to superclass variables, methods, or constructors
  • Used in inheritance

πŸ”§ Example:

class Animal {
    String name = "Animal";
    void speak() {
        System.out.println("Animal speaks");
    }
}

class Dog extends Animal {
    String name = "Dog";
    void printNames() {
        System.out.println(super.name); // Animal
        System.out.println(this.name);  // Dog
    }

    void speak() {
        super.speak(); // Call parent method
        System.out.println("Dog barks");
    }
}

βœ… Use Cases:

  • Call parent constructor using super()
  • Access parent fields/methods overridden by child

πŸ”Ή 5. volatile – Thread Visibility Guarantee

🧠 What is volatile?

  • Used when a variable is shared between multiple threads.
  • Forces all threads to always read/write from main memory.
  • Prevents a thread from using a cached value of a variable.

πŸ’‘ Real-Life Analogy:

Imagine two workers (threads) checking a note (variable). If one keeps a copy in his pocket and the other updates the note on the wall, the first won’t see the change.
With volatile: The worker must always check the wall, not his pocket.

πŸ”§ Simple Example:

class SharedResource {
    volatile boolean running = true;

    void stop() {
        running = false;
    }

    void work() {
        while (running) {
            // do some work
        }
        System.out.println("Thread stopped.");
    }
}

βœ… Use Cases:

  • Used for status flags like running, isActive.
  • When you only need to ensure visibility between threads.
  • Used in multi-threaded applications to share simple variables.

⚠️ Important Notes:

  • volatile does NOT make operations atomic (like x++ is still not thread-safe).
  • If you need both visibility and atomicity, use synchronized or Atomic classes.

πŸ“ Interview Tip:

If asked β€œWhat does volatile do?” say:
β€œIt guarantees visibility of changes to variables across threads β€” all threads see the most recent value.”

πŸ”Ή 6. transient – Exclude from Serialization

🧠 What is Serialization?

Serialization is the process of converting an object into a byte stream so it can be saved to a file or sent over a network.

Deserialization is converting that byte stream back into the original object.

πŸ”‘ What is transient?

  • It prevents a variable from being serialized.
  • Useful when you don’t want to save or expose sensitive or temporary data.

πŸ’‘ Real-Life Example:

Imagine you’re saving a User object to a file. You want to save the name but not the password. So, you mark the password field as transient to hide it.

πŸ”§ Code Example:

import java.io.*;

class User implements Serializable {
    String name;
    transient String password;

    User(String name, String password) {
        this.name = name;
        this.password = password;
    }
}

public class Main {
    public static void main(String[] args) throws Exception {
        User user1 = new User("Deepak", "secret123");

        // Serialize
        FileOutputStream fos = new FileOutputStream("user.txt");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(user1);
        oos.close();

        // Deserialize
        FileInputStream fis = new FileInputStream("user.txt");
        ObjectInputStream ois = new ObjectInputStream(fis);
        User savedUser = (User) ois.readObject();
        ois.close();

        System.out.println("Name: " + savedUser.name);        // Output: Deepak
        System.out.println("Password: " + savedUser.password); // Output: null
    }
}

βœ… Use Cases:

  • Hiding sensitive data like password, OTP, pin
  • Not saving temporary fields (like cache or lastUpdated)
  • Skipping non-serializable fields (e.g., Thread, Socket)

πŸ“ Interview Tip:

Q: What does transient do in Java?
A: It tells the JVM to skip this variable when serializing an object.

πŸ”Ή 7. synchronized – Thread Safety

🧠 What is synchronized?

  • Used in multi-threaded programs to prevent problems when multiple threads access the same resource.
  • Ensures that only one thread

πŸ’‘ Real-Life Analogy:

Think of a toilet in a public restroom. Only one person can go in at a time (it has a lock). The others must wait.
synchronized acts like that lock in your code.

πŸ”§ Example: Safe Counter

class Counter {
    private int count = 0;

    // synchronized method ensures one thread at a time
    synchronized void increment() {
        count++;
    }

    int getCount() {
        return count;
    }
}

πŸ” Two Forms:

// 1. Synchronized Method
synchronized void methodA() {
    // critical code
}

// 2. Synchronized Block
void methodB() {
    synchronized(this) {
        // critical code
    }
}

βœ… Use Cases:

  • Banking systems (update balances safely)
  • Counting visitors to a website
  • Writing to shared files or logs

πŸ“ Interview Tip:

Q: Why is synchronized important?
A: It prevents race conditions by allowing only one thread to access critical code at a time.

πŸ”Ή 8. instanceof – Type Check

🧠 What is instanceof?

  • `instanceof` is a keyword in Java used to check if an object is an instance of a specific class or subclass.
  • Returns true if the object is of that type, otherwise false.
  • Helps in **safe downcasting** to avoid runtime errors.

πŸ’‘ Real-Life Analogy:

Imagine you have a list of animals. You want to perform dog tricks, but only if the animal is a dog. So you check: "Is this animal a Dog?" β†’ That’s what instanceof does.

πŸ”§ Example: Basic Use

class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}

public class Test {
    public static void main(String[] args) {
        Animal a = new Dog(); // a is of type Animal, but actually refers to a Dog

        if (a instanceof Dog) {
            System.out.println("It's a Dog!");
        }

        if (a instanceof Cat) {
            System.out.println("It's a Cat!");
        } else {
            System.out.println("It's NOT a Cat");
        }
    }
}
// Output:
// It's a Dog!
// It's NOT a Cat

πŸ” Example: Safe Downcasting

class Animal {}
class Dog extends Animal {
    void bark() {
        System.out.println("Woof!");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal a = new Dog();

        if (a instanceof Dog) {
            Dog d = (Dog) a; // Safe casting
            d.bark(); // Woof!
        }
    }
}

βœ… Use Cases:

  • Checking object type before casting
  • Used in polymorphism to identify actual object type
  • Prevents ClassCastException at runtime

πŸ“ Interview Tip:

Q: Why is instanceof used in Java?
A: It checks whether an object is of a specific class type to safely perform downcasting and avoid runtime errors.

πŸ“ Final Summary Table

Keyword Purpose Common Use Case
final Prevent change Constants, prevent method override
static Shared by all objects Utility methods, shared counters
this Refers to current object Resolve variable name conflict
super Refers to parent class Inheritance, call parent constructor
volatile Thread-safe visibility Flags in multi-threading
transient Skip during serialization Hide sensitive data
synchronized Thread-safe method/block Avoid race condition
instanceof Check object type before casting Polymorphism, type safety

🎯 Interview Tip: How to Answer

βœ… "Can you explain volatile?"
βœ” Answer: "Yes, volatile is used in multi-threading to ensure that changes to a variable are visible to all threads. Without it, a thread may see a cached value instead of the latest value from memory."
βœ… "Why use transient?"
βœ” Answer: "To prevent fields from being serialized β€” especially helpful when we don't want to store sensitive or temporary data."